import React, { useState, useEffect, useMemo } from 'react';
import cn from 'classnames';
import { Link, useLocation } from 'react-router-dom';
import s from './style.module.css';
import { Menu } from '@knownsec/react-component';
import cookie from 'react-cookies';
import {
  getUserInfoDetail as getUserInfoDetailApi,
  getRoleList as getRoleListApi,
} from '../../../API/index';
const { SubMenu } = Menu;
const allNavs = [
  {
    icon: 'monitor',
    title: '监测列表',
    link: '/monitor',
    subChildren: [
      '/form_page',
      '/securityInfo/',
      '/vul_detail/',
      '/outlink/Detail',
      '/change_detail/',
    ],
  },
  {
    icon: 'task',
    title: '任务管理',
    children: [
      {
        title: '任务队列',
        link: '/task_list',
      },
      {
        title: '任务组',
        link: '/task_group',
        subChildren: ['/task_info/', /form_page.*type=group/],
      },
    ],
  },
  {
    icon: 'alert',
    title: '告警中心',
    link: '/alert_Page',
  },
  {
    icon: 'down',
    title: '报告下载',
    link: '/down',
  },
  {
    icon: 'keyword',
    title: '策略管理',
    children: [
      {
        title: '敏感词',
        link: '/keyword',
      },
      {
        title: '漏洞模版',
        link: '/custom_module',
      },
      {
        title: '变更基准',
        link: '/change_set',
      },
    ],
  },
  {
    icon: 'user',
    title: '用户管理',
    children: [
      {
        title: '用户列表',
        link: '/user_manage',
      },
      {
        title: '账号设置',
        link: '/user_edit',
      },
      {
        title: 'API管理',
        link: '/api_page',
      },
      {
        title: '认证方式',
        link: '/auth_method',
      },
    ],
  },
  {
    icon: 'role',
    title: '角色管理',
    link: '/role_manage',
  },
  {
    icon: 'log',
    title: '日志中心',
    link: '/log_center',
  },
  {
    icon: 'backup',
    title: '备份恢复',
    link: '/backup_recovery',
  },
  {
    icon: 'bug',
    title: '漏洞库',
    link: '/bug_store',
  },
  {
    icon: 'network',
    title: '网络配置',
    children: [
      {
        title: '网口配置',
        link: '/network_config',
      },
      {
        title: '路由配置',
        link: '/router_config',
      },
      {
        title: 'DNS配置',
        link: '/dns_config',
      },
      {
        title: 'SNMP配置',
        link: '/snmp_config',
      },
      {
        title: 'SSH配置',
        link: '/ssh_config',
      },
      // {
      //   title: 'HTTPS配置',
      //   link: '/https_config',
      // },
    ],
  },
  {
    icon: 'update',
    title: '升级服务',
    link: '/system_update',
  },
  {
    icon: 'product',
    title: '系统信息',
    link: '/product_info',
  },
  {
    icon: 'systemStatus',
    title: '系统状态',
    children: [
      {
        title: '系统负载',
        link: '/system_load',
      },
      {
        title: '业务负载',
        link: '/business_load',
      },
      {
        title: '系统时间',
        link: '/system_time',
      },
      {
        title: '系统控制',
        link: '/system_control',
      },
      {
        title: '接口流量',
        link: '/interface_flow',
      },
    ],
  },
  {
    icon: 'remote',
    title: '问题排查',
    children: [
      // {
      //   title: '错误日志',
      //   link: '/error_log',
      // },
      {
        title: '远程协助',
        link: '/remote_help',
      },
    ],
  },
];
const NavDataAdmin = [
  // {
  //   icon: 'monitor',
  //   title: '监测列表',
  //   link: '/monitor',
  //   subChildren: [
  //     '/form_page',
  //     '/securityInfo/',
  //     '/vul_detail/',
  //     '/outlink/Detail',
  //     '/change_detail/',
  //   ],
  // },
  {
    icon: 'keyword',
    title: '策略管理',
    children: [
      {
        title: '敏感词',
        link: '/keyword',
      },
      {
        title: '漏洞模版',
        link: '/custom_module',
      },
      {
        title: '变更基准',
        link: '/change_set',
      },
    ],
  },
  {
    icon: 'user',
    title: '用户管理',
    children: [
      {
        title: '用户列表',
        link: '/user_manage',
      },
      {
        title: '账号设置',
        link: '/user_edit',
      },
      {
        title: 'API管理',
        link: '/api_page',
      },
      {
        title: '认证方式',
        link: '/auth_method',
      },
    ],
  },
  {
    icon: 'role',
    title: '角色管理',
    link: '/role_manage',
  },
  {
    icon: 'network',
    title: '网络配置',
    children: [
      {
        title: '网口配置',
        link: '/network_config',
      },
      {
        title: '路由配置',
        link: '/router_config',
      },
      {
        title: 'DNS配置',
        link: '/dns_config',
      },
      {
        title: 'SNMP配置',
        link: '/snmp_config',
      },
      {
        title: 'SSH配置',
        link: '/ssh_config',
      },
    ],
  },
  {
    icon: 'update',
    title: '升级服务',
    link: '/system_update',
  },
  {
    icon: 'product',
    title: '系统信息',
    link: '/product_info',
  },
  {
    icon: 'systemStatus',
    title: '系统状态',
    children: [
      {
        title: '系统负载',
        link: '/system_load',
      },
      {
        title: '业务负载',
        link: '/business_load',
      },
      {
        title: '系统时间',
        link: '/system_time',
      },
      {
        title: '系统控制',
        link: '/system_control',
      },
      {
        title: '接口流量',
        link: '/interface_flow',
      },
    ],
  },
  {
    icon: 'remote',
    title: '问题排查',
    children: [
      {
        title: '远程协助',
        link: '/remote_help',
      },
    ],
  },
];
const NavDataActive = [
  {
    icon: 'monitor',
    title: '监测列表',
    link: '/monitor',
    subChildren: [
      '/form_page',
      '/securityInfo/',
      '/vul_detail/',
      '/outlink/Detail',
      '/change_detail/',
    ],
  },
  {
    icon: 'asset',
    title: '任务管理',
    children: [
      {
        title: '任务队列',
        link: '/task_list',
      },
      {
        title: '任务组',
        link: '/task_group',
        subChildren: ['/task_info/', /form_page.*type=group/],
      },
    ],
  },
  {
    icon: 'alert',
    title: '告警中心',
    link: '/alert_Page',
  },
  {
    icon: 'down',
    title: '报告下载',
    link: '/down',
  },
  {
    icon: 'user',
    title: '用户管理',
    children: [
      {
        title: '用户列表',
        link: '/user_manage',
      },
      {
        title: '账号设置',
        link: '/user_edit',
      },
      {
        title: 'API管理',
        link: '/api_page',
      },
      {
        title: '认证方式',
        link: '/auth_method',
      },
    ],
  },
  {
    icon: 'bug',
    title: '漏洞库',
    link: '/bug_store',
  },
  {
    icon: 'product',
    title: '系统信息',
    link: '/product_info',
  },
];
const NavDataAudit = [
  {
    icon: 'user',
    title: '用户管理',
    children: [
      {
        title: '用户列表',
        link: '/user_manage',
      },
      {
        title: '账号设置',
        link: '/user_edit',
      },
      {
        title: 'API管理',
        link: '/api_page',
      },
      {
        title: '认证方式',
        link: '/auth_method',
      },
    ],
  },
  {
    icon: 'log',
    title: '日志中心',
    link: '/log_center',
  },
  {
    icon: 'bug',
    title: '漏洞库',
    link: '/bug_store',
  },
  {
    icon: 'product',
    title: '系统信息',
    link: '/product_info',
  },
];

function Nav() {
  let pathName = useLocation().pathname;
  pathName = '/dashboard/'.includes(pathName) ? '/monitor' : pathName;
  const mathKey = NavDataAdmin.reduce((total, item, index) => {
    if (item.children) {
      item.children.map((i) => {
        if (i.subChildren) {
          i.subChildren.map((s) => {
            if (typeof s === 'object') {
              if (s.test(useLocation().pathname + useLocation().search)) {
                // 子页面共用时通过url匹配正则确认高亮菜单
                total = index;
                pathName = i.link;
              }
            } else {
              if (pathName.includes(s)) {
                total = index;
                pathName = i.link;
              }
            }
          });
        } else if (i.link === pathName) total = index;
      });
    } else {
      if (item.subChildren) {
        item.subChildren.map((s) => {
          if (typeof s === 'object') {
            if (s.test(useLocation().pathname + useLocation().search)) {
              total = index;
              pathName = item.link;
            }
          } else {
            if (pathName.includes(s)) {
              total = index;
              pathName = item.link;
            }
          }
        });
      } else if (item.link === pathName) total = index;
    }
    return total;
  }, 0);
  const [openKeys, setOpenKeys] = useState('' + mathKey || '');
  const [collapsed, setCollapsed] = useState(false);
  const [navData, setNavData] = useState(NavDataAdmin);
  const selIcon = useMemo(() => {
    return pathName.replace('/', '');
  }, [pathName]);

  const Navicon = (icon) => {
    if (selIcon.includes(icon)) {
      return <div className={cn(s.baseSel, icon ? s[icon] : '')}></div>;
    } else {
      return <div className={cn(s.baseNoSel, icon ? s[icon] : '')}></div>;
    }
  };
  // const [currentUserId, setCurrentUserId] = useState('');
  let currentUserId = '';
  const getUserInfoDetail = async () => {
    try {
      const { data } = await getUserInfoDetailApi();
      currentUserId = data.user_group_id;
    } catch (err) {
      console.log(err);
    }
  };
  const roleListParams = {
    page: 1,
    pageSize: 10,
    userGroupId: '',
  };
  const setPermissionList = async () => {
    try {
      roleListParams.userGroupId = currentUserId;
      console.log(currentUserId, roleListParams);
      const { data } = await getRoleListApi(roleListParams);
      const resNavs = data.data[0].modules;
      const currentNavs = [];
      allNavs.forEach((item) => {
        const matchNav = resNavs.find((subItem) => subItem.module_name === item.title);
        if (matchNav) {
          currentNavs.push(item);
        }
      });
      setNavData(currentNavs);
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(async () => {
    await getUserInfoDetail();
    if (localStorage.group === '操作员') {
      setNavData(NavDataActive);
    } else if (localStorage.group === '审计员') {
      setNavData(NavDataAudit);
    } else if (localStorage.group === '管理员') {
      setNavData(NavDataAdmin);
    } else {
      setPermissionList();
    }
  }, []);
  return (
    <Menu
      openKeys={[openKeys]}
      selectedKeys={pathName}
      mode="inline"
      theme="dark"
      inlineCollapsed={collapsed}
      className={s.navBox}
      multiple={false}
      onOpenChange={(e) => {
        setOpenKeys(e.pop());
      }}
      style={collapsed ? { width: '80px' } : { width: '152px' }}
      onClick={(item) => {
        if (item.keyPath.length === 1) setOpenKeys('');
      }}
    >
      <div
        className={s.navBtn}
        onClick={(e) => {
          if (e.target.getAttribute('id') === 'collIcon') {
            setCollapsed(!collapsed);
            if (collapsed) {
              e.target.parentNode.parentNode.parentNode.nextSibling.style.minWidth =
                'calc(100% - 152px)';
              e.target.parentNode.parentNode.parentNode.nextSibling.style.marginLeft = '152px';
            } else {
              e.target.parentNode.parentNode.parentNode.nextSibling.style.minWidth =
                'calc(100% - 80px)';
              e.target.parentNode.parentNode.parentNode.nextSibling.style.marginLeft = '80px';
            }
          }
        }}
      >
        <div
          className={s.navImg}
          id="collIcon"
          style={{ 'background-position': collapsed ? '100% 0' : '90% 0' }}
        ></div>
      </div>
      {navData.map((e, i) => {
        if (e.children) {
          return (
            <SubMenu key={i} icon={Navicon(e.icon)} title={e.title} className={s.Menu}>
              {e.children.map((e_) => {
                return (
                  <Menu.Item key={e_.link}>
                    <Link to={e_.link}>{e_.title}</Link>
                  </Menu.Item>
                );
              })}
            </SubMenu>
          );
        } else {
          return (
            <Menu.Item key={e.link} className={s.Menu} icon={Navicon(e.icon)}>
              <Link to={e.link}>{e.title}</Link>
            </Menu.Item>
          );
        }
      })}
    </Menu>
  );
}
export default Nav;
